package com.techysky.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Properties;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * IETM模块xml解析
 * @author zhangxu
 *
 */
public class IetmUtils implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;  
	private static Log log=LogFactory.getLog(IetmUtils.class);
	private static TransformerFactory factory=TransformerFactory.newInstance();
	private IetmUtils(){}
	
    /**   
     * JavaBean转换成xml   
     * @param obj   
     * @param encoding "UTF-8"   
     * @return    
     */
	public static String bean2Xml(Object obj, String encoding) {    
        String result = null;    
        try {    
            JAXBContext context = JAXBContext.newInstance(obj.getClass());    
            Marshaller marshaller = context.createMarshaller();    
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);    
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);    
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);  
            StringWriter writer = new StringWriter();    
            marshaller.marshal(obj, writer);    
            result = writer.toString();    
        } catch (Exception e) {    
            log.info(e);  
        }    
        return result;    
    }    
    
    /**   
     * xml转换成JavaBean   
     * @param xml  
     * @param c   
     * @return   
     */    
    @SuppressWarnings("unchecked")    
    public static <T> T xml2Bean(String xml, Class<T> clzz) {    
        T t = null;    
        try {    
            JAXBContext context = JAXBContext.newInstance(clzz);    
            Unmarshaller unmarshaller = context.createUnmarshaller();    
            t = (T) unmarshaller.unmarshal(new StringReader(xml));    
        } catch (Exception e) {    
           log.info(e); 
        }    
    
        return t;    
    }    
    
    /**
     * xml转换成JavaBean
     * @param file
     * @param clzz
     * @return
     */
    @SuppressWarnings("unchecked")    
    public static <T> T  xml2Bean(File file, Class<T> clzz) {    
        T t = null;    
        try {    
            JAXBContext context = JAXBContext.newInstance(clzz);    
            Unmarshaller unmarshaller = context.createUnmarshaller();    
            t = (T) unmarshaller.unmarshal(file);    
        } catch (Exception e) {    
            log.info(e);   
        }    
        return t;    
    }
    
    /**
     * 
     * @param xml
     * @param xsl
     * @param dir
     */
    public static String  gengeryHtml(File xml,File xsl,String dir) {
    	try {
    		File file=new File(dir);
    		if(!file.exists()) {
    			file.mkdirs();
    		}
    		String htmlName=xml.getName().substring(0,xml.getName().indexOf('.'))+".html";
    		factory.newTransformer(new StreamSource(xsl)).transform(new StreamSource(xml), new StreamResult(new FileOutputStream(dir+htmlName)));
    		return htmlName;
    	} catch (Exception e) {
			log.info(e);
			return null;
		}
    }
    /**
     * 匹配文件名第8位来确认是哪一种Dm,暂时未用，理由行不通
     * @param code
     * @return
     * @throws FileNotFoundException 
     */
    public static String dmType(String code) {
    	Properties pps=new Properties();
    	String value="";
    	try {
    		pps.load(new InputStreamReader(IetmUtils.class.getClassLoader().getResourceAsStream("ic.properties"), "UTF-8"));
			Enumeration<?> enums= pps.propertyNames();
	    	while (enums.hasMoreElements()) {
				String key = enums.nextElement().toString();
				if(key.equals(code)){
					value=pps.getProperty(key);
				}
			}
    	} catch (Exception e) {
			log.info(e);
		} 
    	return value;
    } 
    /**
     * 解析根据隐痛的xsd判断每个xml对应的dm
     * @param file
     * @return
     */
    public static String dmType(File file) {
    	SAXReader reader = new SAXReader();              
        try {
			Document document = reader.read(file);
			Element element=document.getRootElement();
			String root=element.attribute("noNamespaceSchemaLocation").getText();
			return root.substring(root.lastIndexOf('/')+1,root.lastIndexOf('.'));
		} catch (DocumentException e) {
			log.info(e);
		}  
		return "";
    	
    }
 
    /**
     * sns
     * @param code
     * @return
     */
    public static String sns(String code){
    	Properties pps=new Properties();
    	String value="";
    	try {
			pps.load(new InputStreamReader(IetmUtils.class.getClassLoader().getResourceAsStream("sns.properties"), "UTF-8"));
			Enumeration<?> enums=pps.propertyNames();
	    	while (enums.hasMoreElements()) {
				String key =  enums.nextElement().toString();
				if(key.equals(code)){
					value=pps.getProperty(key);
				}
			}
    	} catch (Exception e) {
			log.info(e);
		} 
    	return value;
    }
  }